import { EventBase } from "../../cccframework/Common/Components/EventBase";
import { Intersection } from "../../cccframework/Common/Components/Intersection";
import { gameHelper } from "../../cccframework/Utils/GameHelpler";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Geometry extends cc.Component {
    @property(cc.Node)
    polygon: cc.Node = null;
    @property(cc.Node)
    point: cc.Node = null;

    onLoad() {
        let ctx = gameHelper.getDebugSceneCtx();
        // this.point.addComponent(EventBase).registerEvent();
        // for (let i of this.polygon.children) {
        //     i.addComponent(MoveEvent).registerEvent();
        // }
        [this.point].concat(this.polygon.children).forEach(v => {
            v.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
        })
    }

    touchMove(touch: cc.Event.EventTouch) {
        let node = touch.currentTarget;
        node.worldPosition = touch.getLocation();
    }

    public drawLine(p0, p1) {
        let ctx = gameHelper.getDebugSceneCtx();
        // ctx.clear();
        ctx.moveTo(p0.x, p0.y);
        ctx.lineTo(p1.x, p1.y);
        ctx.stroke();
    }

    public drawPolygon() {

    }

    update(dt) {
        let ctx = gameHelper.getDebugSceneCtx();
        ctx.clear();
        let polygon = [];

        for (let i = 0; i < this.polygon.children.length; i++) {
            polygon.push(this.polygon.children[i].position);
        }
        ctx.strokeColor = cc.color(255, 255, 0);
        if (Intersection.pointInPolygon(this.point.position, polygon)) {
            ctx.strokeColor = cc.color(255, 0, 0);
        }
        for (let i = 0; i < this.polygon.children.length; i++) {
            let p0 = this.polygon.children[i];
            let p1 = i == this.polygon.childrenCount - 1 ? this.polygon.children[0] : this.polygon.children[i + 1];
            this.drawLine(p0.position, p1.position);
        }
    }
}
